﻿using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Sustainalytics.Entities.RiskRatings;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Xml.Linq;

namespace Sustainalytics.ClientDW.Synchronization.SyncRiskRatingsData.Events
{
    public class IncidentsQuery 
    {
        private int _commandTimeout;
        private SqlDatabase _database;
        public IncidentsQuery(SqlDatabase sqlDatabase)
        {
            _database = sqlDatabase ?? throw new Exception("Sql Connection string must be provided!");
            _commandTimeout = 3600;
        }

        public IEnumerable<Incident> Get(List<Guid> companyIds)
        {
            var incidents = new List<Incident>();

            using (var reader = Incidents(companyIds))
            {
                if (reader == null) return incidents;

                while (reader.Read())
                {
                    var incident = new Incident
                    {
                        Id = (Guid)reader["Id"],
                        CompanyId = (Guid)reader["CompanyId"],
                        EventIndicatorId = (Guid)reader["EventIndicatorId"],
                        IncidentId = (string)reader["IncidentId"],
                        Name = (string)reader["Name"],
                        MainTag = (string)reader["MainTag"],
                        Source = (string)reader["Source"],
                        IncidentDate = (DateTime)reader["IncidentDate"],
                        Location = new Location
                        {
                            Address = (string)reader["LocationAddress"],
                            Latitude = (double)reader["LocationLatitude"],
                            Longitude = (double)reader["LocationLongitude"]
                        },
                        IsMain = (bool)reader["IsMajorIncidentInChain"],
                        ExternalUrl = reader["ExternalUrl"] as string ?? string.Empty
                    };
                    incidents.Add(incident);
                }
            }

            return incidents;
        }

        private IDataReader Incidents(List<Guid> companyIds)
        {
            var command = new SqlCommand
            {
                CommandText = "spGetIncidentsByCompanyIds",
                CommandType = CommandType.StoredProcedure,
                CommandTimeout = _commandTimeout
            };

            var ids = new XElement("CompanyIds", companyIds.Select(id => new XElement("Id", id)));

            command.Parameters.AddWithValue("@CompanyIds", ids.ToString());

            return _database.ExecuteReader(command);
        }
    }
}